<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :inline="true"  >
      <el-form-item label="业务类型:" prop="type" >
          <el-select v-model="form.type" placeholder="请选择业务类型" clearable>
              <el-option v-for="i in businessOptions" :key="i.key" :label="i.name" :value="i.key"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="银行:" prop="bankId">
          <el-select v-model="form.bankId" placeholder="请选择银行" filterable clearable>
              <el-option v-for="i in bankOptions" :key="i.id" :label="i.name" :value="i.id"></el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="企业名称:" prop="entName">
        <el-select
          style="width: 280px;"
          @change="entNameChange"
          v-model="form.entName"
          filterable
          remote
          clearable
          placeholder="请输入企业名称"
          :remote-method="remoteMethod"
          :loading="entNameLoading">
          <el-option
            v-for="item in entNameOptions"
            :key="item.uniscid"
            :label="item.name"
            :value="item.uniscid + '@name' + item.name + '@region' + item.region">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区县:" prop="region">
          <el-select v-model="form.region" placeholder="请选择区县" clearable style="width: 120px;">
              <el-option v-for="i in cityOptions" :key="i.key" :label="i.name" :value="i.name"></el-option>
          </el-select>
      </el-form-item>
      <!-- <el-form-item label="录入人:" prop="username">
          <el-input  v-model="form.username" placeholder="请输入录入人姓名"></el-input>
      </el-form-item> -->
      <el-form-item label="创建日期:" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            style="width: 280px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="success" @click="add">录入</el-button>
        <el-button type="info"  @click="download">导出</el-button>
      </el-form-item>
      <!-- <el-form-item label="合同上传:">
        <el-upload
            ref="upload"
            accept=".doc,.docx"
            class="upload-demo"
            :file-list="fileList"
            :limit="1"
            :on-success="onSuccess"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :with-credentials="true"
            action="https://www.zbifc.com/sso/mh/app/xmfb/upFile"
            multiple>
            <el-button v-if="!isReview" class="el-upload__btn" size="small" type="primary">点击上传</el-button>
            <div v-if="!isReview" class="el-upload__tip" slot="tip">只能上传doc/.docx文件，最多上传两个文件</div>
        </el-upload>
      </el-form-item> -->
    </el-form>
    
    <Table 
        ref="Table" 
        :tableData="tableData" 
        :tableHeadData="tableHeadData" 
        v-loading="tableLoading"
        @getList="getTableList" 
        :total="total"
    />
  </div>
</template>

<script>
import { cityOptions,businessOptions,parseTime } from '@/utils/index'
import { getBanks,getEnterprise,getBusinessList,businessDelete,businessDownload } from '@/api/user'
import Table from '@/components/table/table.vue';

export default {
  components:{
    Table
  },
  data() {
    return {
      form: {
        type: '',
        region: '',
        //username:'',
        bankId:'',
        entName:'',
        dateRange:''
      },
      cityOptions:Object.freeze(cityOptions),
      businessOptions:Object.freeze(businessOptions),
      bankOptions:[],
      entNameOptions:[],
      entNameLoading:false,
      tableData:[],
      tableHeadData:[],
      tableLoading:false,
      currentPageParams:{
          'pageNum': 1,
          'pageSize': 10
      },
      total:0
    }
  },
  watch: {
    $route(to, from) {
        window.location.reload(); //监测到路由发生跳转时刷新一次页面
    },
  },
  async mounted(){
    await this.getBanks()
    this.search();
  },
  methods: {
    async getTableList({ pageSize = 10, pageNum = 1 } = this.currentPageParams) {
      this.tableLoading = true;
      const condition = this.getCondition();
      const params = {
        rows:pageSize,
        page:pageNum,
        bzParam:{
          ...condition
        }
      };
      //console.log('getTableList', params)
      //return
      const res = await getBusinessList(params);
      const { data } = res;
      //const data = await this.iDMapServer.getTestData('taskList');
      console.log('data', data)
      this.tableData = data.rows
      this.data = this.fomatData(data.rows);

      this.total = data.total;
      this.tableHeadData = this.createTableHeadData(data.rows[0]);
      this.tableLoading = false;
      //this.$nextTick(_ => this.$refs.Table.doLayout()); //重绘表格 数据变动后表格头错乱
    },
    createTableHeadData(data) {
      const tableHeadData = [];
      for (let i in data) {
        let obj = {};
        switch (i) {
          case 'entName':
            obj.prop = i;
            obj.label = '企业名称'
            //obj.isLink = true; 
            obj.minWidth = '60';
            obj.tableOrder = 13
            break
          case 'region':
            obj.prop = i;
            obj.label = '区县'
            obj.tableOrder = 16
            obj.minWidth = '20'
            break
          case 'money':
            obj.prop = i;
            obj.label = '金额（万元）'
            obj.tableOrder = 17
            obj.minWidth = '40'
            break
          case 'bankName':
            obj.prop = i;
            obj.label = '银行'
            obj.tableOrder = 18
            obj.minWidth = '40'
            break  
          case 'contractNo':
              obj.prop = i;
              obj.label = '委托合同号'
              obj.tableOrder = 18
              obj.minWidth = '50'
            break
          case 'type':
              obj.prop = i;
              obj.label = '业务类型'
              obj.tableOrder = 18
              obj.minWidth = '30'
            break 
          case 'username':
            obj.prop = i;
            obj.label = '录入人'
            obj.tableOrder = 18
            obj.minWidth = '20'
            break  
          case 'createTime':
              obj.prop = 'createtime_view';
              obj.label = '创建时间'
              obj.tableOrder = 19
              obj.minWidth = '30'
            break    
          default:
            continue;
            break;
        }
        tableHeadData.push(obj);
      }

      tableHeadData.push({  
          prop:'operate',
          label:'操作',
          tableOrder : 50,
          minWidth:'60',
          operation:[
              {name: '查看', colorType:'info', clickFun: this.detailRow},
              {name: '编辑', colorType:'warning', clickFun: this.editRow},
              {name: '删除', colorType:'danger', clickFun: this.deleteRow},
              {name: '合同上传', colorType:'success', width:"80px",clickFun:this.uploadContract}
          ]
      });
      // tableHeadData.push({
      //     prop:'operate',
      //     label:'操作',
      //     tableOrder : 7,
      //     minWidth:'170',
      //     operation:[],
      //     hasCustomize:true,
      //     customize:tablePro,
      //     prop1:this.IDMapServer,
      //     prop2:''
      // });
      tableHeadData.sort((a, b) => a.tableOrder - b.tableOrder);
      return Object.freeze(tableHeadData)
    },
    fomatData(data){
      data.forEach(element => {
        //element.bankid_view = element.bankId ? this.bankOptions.find(i => i.id === element.bankId).name : null;
        //element.createtime_view = element.createTime ? element.createTime.slice(0,10) + '  ' + element.createTime.slice(12,16) : null
        element.createtime_view = element.createTime ? parseTime(new Date(element.createTime).getTime(), '{y}-{m}-{d} {h}:{i}') : null
      });
    },
    search() {
      this.getTableList(this.currentPageParams)
      //console.log('params',params)
    },
    getCondition(){      
      for(let i in this.form){
        if(i === 'dateRange'){
          if(!this.form[i] === ''){
            this.form['startTime'] = null;
            this.form['endTime'] = null;
          }else{
            this.form['startTime'] = this.form[i][0]
            this.form['endTime'] = this.form[i][1]
          }
        }else{  
          if(this.form[i] === ''){
            this.form[i] = null;
          }
        }
        
      }
      return this.form
      //this.render()
    },
    async getBanks(){
      const data = await getBanks();
      this.bankOptions = data.data;
    },
    async remoteMethod(query) {
      if (query !== '') {
        this.entNameLoading = true;
        const params = {
          name:query
        }
        const res = await getEnterprise(params);
        console.log('res',res)
        if(res.message === 'SUCCESS')
          this.entNameLoading = false;
          this.entNameOptions = res.data;
          // setTimeout(() => {
          //   this.entNameLoading = false;
          //   this.entNameOptions = this.list.filter(item => {
          //     return item.label.toLowerCase()
          //       .indexOf(query.toLowerCase()) > -1;
          //   });
          // }, 200);
        } else {
          this.entNameOptions = [];
        }
    },  
    entNameChange(data){
      console.log('entNameChange',data);
      const region = data.slice(data.indexOf('@region') + 7,data.length);
      const entName = data.slice(data.indexOf('@name') + 5,data.indexOf('@region'));
      this.form.region = region;
      this.form.entName = entName
      console.log('region',region);
    },
    detailRow(row){
      const { id } = row;
      this.$router.push({
        path:'businessForm',
        query:{
          action:'check',
          id
        }
      })
  
    },
    editRow(row){
      const { id } = row;
      this.$router.push({
        path:'businessForm',
        query:{
          action:'edit',
          id
        }
      })
      // const routeData = this.$router.resolve({
      //     path:'/businessForm',
      //     query: {
      //       id:row.id,
      //       action:'edit'
      //     },
      // });
      // window.open(routeData.href, '_blank');
    },
    deleteRow(row){
      const { id } = row;
      this.$confirm(`确定删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        
        businessDelete({ id }).then(res => {
          const { message, msg } = res;
          console.log('res',res);
          if (message === 'SUCCESS') {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.search()
          } 
        })
      }).catch(() => {

      });
    },
    async download(){
      const condition = this.getCondition();
      const response = await businessDownload(condition)
      const res = response.data
      console.log('data',response);
      const excelUrl = window.URL.createObjectURL(new Blob([res]));
      const link = window.document.createElement('a');
      const fileName = JSON.parse(response.config.data).fileName || '业务信息'; // 文件名
      const suffix = JSON.parse(response.config.data).suffix || 'xlsx'; // 文件后缀
      const isDownload = JSON.parse(response.config.data).isDownload; // 是否是下载（如果不是下载则为导出）
      link.href = excelUrl;
      link.download = `${fileName}.${suffix ? suffix : 'xlsx'}`;
      document.body.appendChild(link); // 兼容FireFox
      link.click();
      window.URL.revokeObjectURL(excelUrl);
      link.remove(); // 兼容FireFox
      console.log(isDownload ? '下载成功！' : '导出成功！')
      // return Promise.resolve(res)
    },
    uploadContract(row){
      const { id } = row;
      this.$router.push({
        path:'/contractForm',
          query: {id},
      })
    },
    add() {
      this.$router.push({
        path:'businessForm',

      })

    },
    
  }
}
</script>

<style scoped lang="scss">
 ::v-deep .pagination {
  .el-pagination{
    text-align: center;
  }
 }
 
// /deep/ .el-col-lg-4-8 {
//         width: 20%;
//     }
</style>

